package com.zsd.android.common

import android.util.SparseArray
import android.view.View
import android.widget.Button
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView

open class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    //等同于HashMap<Integer, View>
    private val views: SparseArray<View>

    init {
        views = SparseArray()
    }

    /**
     * 给View设置监听事件
     *
     * @param viewId
     * @param adapter Adapter，可以让同一个Activity中区别不同Adapter的Item点击事件
     * @param tag 设置标识，可以自己设置用来区别Item
     */
    fun setOnClickListener(viewId: Int, adapter: BaseRvAdapter<*>, tag: Int) {
        getView<View>(viewId).setOnClickListener {
            adapter.onClickItemListener?.onClickItem(adapter, it, layoutPosition, tag)
        }
    }

    /**
     * 给View设置Text
     *
     * @param viewId
     * @param txt 内容
     */
    fun  setText(viewId: Int, txt: String) {
        var view = getView<View>(viewId)
        if (view is TextView) {
            view.setText(txt)
        } else if (view is Button) {
            view.setText(txt)
        }
    }

    /**
     * 给View设置图片
     *
     * @param viewId
     * @param resId 图片资源id
     */
    fun setImageRes(viewId: Int, resId: Int) {
        var view = getView<View>(viewId)
        if (view is ImageView) {
            view.setImageResource(resId)
        } else if (view is ImageButton) {
            view.setImageResource(resId)
        }
    }

    /**
     * 显示View
     *
     * @param viewId
     */
    fun showView (viewId: Int) {
        var view = getView<View>(viewId)
        if (!view.isVisible) {
            view.visibility = View.VISIBLE
        }
    }

    /**
     * 隐藏View，默认是GONE
     *
     * @param viewId
     * @param visibility
     */
    fun hideView(viewId: Int, visibility: Int = View.GONE) {
        var view = getView<View>(viewId)
        if (view.isVisible) {
            view.visibility = visibility
        }
    }

    /**
     * 获取View，如果没有就添加到缓存中
     *
     * @param viewId view的id
     * @return view
     */
    fun <T : View> getView(viewId: Int) : T {
        var view = views.get(viewId)
        if (view == null) {
            view = itemView.findViewById(viewId)
            views.put(viewId, view)
        }
        return view as T
    }

    /**
     * 清空缓存的View
     */
    fun clear() {
        views.clear()
    }
}